// This file is a part of ChaosDB.
// Copyright (C) 2012 ChaoJianPeng
// email:chaojianpeng@gmail.com
//
// ChaosDB is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// ChaosDB is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

/*
 * server.cpp
 *
 *  Created on: 2012-3-2
 *      Author: chao
 */

#include "server.h"
#include "cmalloc.h"

const char error[6] = "error";

void start_server(const char* ip) {
	void *context = zmq_init(1);
	void *responder = zmq_socket(context, ZMQ_REP);
	//监听端口
	zmq_bind(responder, ip);

	while (true) {
		// 等待客户端信息
		zmq_msg_t request;
		zmq_msg_init(&request);
		// 接收客户端消息
		zmq_recv(responder, &request, 0);

		// 执行命令
		Result* res = common(&request);

		zmq_msg_close(&request);
		// 回复
		zmq_msg_t reply;
		zmq_msg_init_size(&reply, res->len);
		memcpy(zmq_msg_data(&reply), res->buff, res->len);

		// 回收一下
		free(res->buff);
		free(res);
//		printf("使用内存%d\n",getUsed());
		// 发送回复
		zmq_send(responder, &reply, 0);
		zmq_msg_close(&reply);

	}
	zmq_close(responder);
	zmq_term(context);
}

